package cmd

import (
	"fmt"
	"sort"

	"github.com/gookit/color"
	"starsine.cn/appTpl/cmn/gcli/v3"
)

// ///////// "github.com/gookit/gcli/v3"
var gCliApp *gcli.App = nil

func GCliStart() *gcli.App {
	gCliApp = gcli.NewApp()
	gCliApp.Version = "1.0.0"
	gCliApp.Desc = "appTpl app commands."

	gCliApp.Add(Help)

	return gCliApp
}

var Help = &gcli.Command{
	Func:    helpExecute,
	Name:    "help",
	Aliases: []string{"h", "hlp"},
	Desc:    "show command list and command summary.",
	Examples: `
	help
`,
	Config: func(c *gcli.Command) {
		c.AddArg("arg0", "command name", false)
	},
}

func helpExecute(c *gcli.Command, args []string) (string, error) {
	info := ""
	magentaln := color.Magenta.Println
	color.Infoln("HELP")

	arr := c.Arg("arg0")
	if arr.Value.String() != "" {
		gCliApp.ShowCommandHelp(arr.Value.String())
		c.Arg("arg0").SetValue("")
		return "", nil
	}

	color.Cyanln("All Commands:")
	cmdList := []string{}
	for k, v := range gCliApp.Commands() {
		cmdList = append(cmdList, fmt.Sprintf("%-20s: %s %s", k, v.Aliases, v.Desc))
	}
	sort.Slice(cmdList, func(i, j int) bool {
		return cmdList[i] < cmdList[j]
	})
	for c, cmdstr := range cmdList {
		info += fmt.Sprintf("(%-2d) %s\n", c, cmdstr)
	}

	magentaln(info)
	return "example output", nil
}
